﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Loader : MonoSingleton<Loader>,IManager
{
    private List<Coroutine> cache;

    public void Init()
    {
        cache = new List<Coroutine>();
    }

    public void UnInit()
    {
        foreach (var cor in cache)
        {
            StopCoroutine(cor);
        }
        cache.Clear();
        Resources.UnloadUnusedAssets();
    }

    public void LoadAsyn<T>(string name,Action<T> callback) where T:UnityEngine.Object
    {
        var cor = StartCoroutine(Load<T>(name, callback));
        cache.Add(cor);
    }

    public T LoadDirect<T>(string name) where T:UnityEngine.Object
    {
        return Resources.Load<T>(name);
    }

    private IEnumerator Load<T>(string name, Action<T> callback) where T : UnityEngine.Object
    {
        ResourceRequest request = Resources.LoadAsync<T>(name);
        while (!request.isDone)
        {
            yield return new WaitForEndOfFrame();
        }
        callback?.Invoke(request?.asset as T);
    }
}
